﻿// //  ********************************************************************************
// //  Copyright (C) 2016 Sebastian Kenter. All rights reserved.
// // 
// //  Name    : PhotonServerProject | PhotonServerFramework | ServerResponseForwardHandler.cs
// //  Created : 2016 - 03 - 22 16:48
// //  Modified: 2016 - 04 - 18 09:38
// //  ********************************************************************************

using System;
using ExitGames.Logging;
using Photon.SocketServer;
using PhotonServerCommon.Enums;
using PhotonServerFramework.Implementation.Client;
using PhotonServerFramework.Implementation.Telegram;
using PhotonServerFramework.Interfaces.Client;
using PhotonServerFramework.Interfaces.Server;
using PhotonServerFramework.Interfaces.Telegram;

namespace PhotonServerFramework.Implementation.Handler.Forward
{
    public class ServerResponseForwardHandler : ServerTelegramHandler
    {
        public override ILogger Logger { get; }
        public override Guid HandlerId { get; set; } = Guid.NewGuid();
        public override HandlerTypes HandlerType => HandlerTypes.Response;
        public override byte HandlerCode => (byte) OperationCodes.ForwardResponse;
        public override int HandlerSubCode => (int) OperationSubCodes.None;
        private readonly IClientPeerRegistry _clientPeerRegistry;

        public ServerResponseForwardHandler(ILogger logger, IClientPeerRegistry clientPeerRegistry)
        {
            Logger = logger;
            _clientPeerRegistry = clientPeerRegistry;
        }

        public override bool HandleTelegram(ITelegram telegram, IServerPeer serverPeer)
        {
            Logger.InfoFormat("Trying to handle telegram of type={0} with code={1}, subcode={2}", telegram.Type,
                telegram.TelegramCode, telegram.TelegramSubCode);

            bool handled = false;

            ClientPeer peer = _clientPeerRegistry.GetClientPeerById(
                Guid.Parse(telegram.TelegramParameters[(byte) ParameterCodes.ClientPeerId].ToString())) as ClientPeer;

            ResponseTelegram response = telegram as ResponseTelegram;

            if (peer != null && response != null)
            {
                peer.SendOperationResponse(
                    new OperationResponse(response.TelegramCode, response.TelegramParameters)
                    {
                        DebugMessage = response.DebugMessage,
                        ReturnCode = response.ReturnCode
                    }, new SendParameters());
                handled = true;
            }

            return handled;
        }
    }
}
